//
//  Location.m
//  LocomotiveGuards
//
//  Created by apple on 15/12/9.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "Location.h"
#import <CoreLocation/CoreLocation.h>
#import "WGS84TOGCJ02.h"


@interface Location ()<CLLocationManagerDelegate>
{
    CLLocationManager * _locationManager;
}

@property (nonatomic,strong) CLGeocoder * geocoder;
@property (nonatomic,assign) CGFloat latitude;      //纬度
@property (nonatomic,assign) CGFloat longitude;     //经度

@end
@implementation Location

-(instancetype)init
{
    if ( self = [super init] )
    {
        _geocoder=[[CLGeocoder alloc]init];
        if ([CLLocationManager locationServicesEnabled])
        {
            _locationManager = [[CLLocationManager alloc]init];
            
            /**
             *  OS8系统后需要添加以下三行代码，plist文件也需要修改
             */
            if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
            {
                [_locationManager requestWhenInUseAuthorization];
            }
            
            _locationManager.desiredAccuracy = 0.1;//kCLLocationAccuracyBest;
            _locationManager.distanceFilter = 10;
            _locationManager.delegate = self;
            [_locationManager startUpdatingLocation];
        }
    }
    return self;
}

- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation * curPostion = nil;
    curPostion = locations.firstObject;
    
    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        self.latitude  = curPostion.coordinate.latitude;
        self.longitude = curPostion.coordinate.longitude;
    }
    else
    {
        GPSLocation location = transformFromWGSToGCJ(LocationMake(curPostion.coordinate.latitude, curPostion.coordinate.longitude));
        self.latitude  = location.lat;
        self.longitude = location.lng;
    }
    
    
    [self getAddressByLatitude:self.latitude longitude:self.longitude];
}

#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        _detailAddress = placemark.name;[NSString stringWithFormat:@"%@%@",placemark.thoroughfare,placemark.subThoroughfare];
        _locality      = placemark.locality;
        _subLocality   = placemark.subLocality;
        NSLog(@"详细信息:%@",placemark.addressDictionary);
    }];
}

-(void)dealloc
{
    [_locationManager stopUpdatingLocation];
}
@end
